#pragma once

#include <iostream>
#include <functional>

#include <signal.h>

#include "Sock.hpp" 

class HttpServer
{
public:
    typedef std::function<void(int)> func_t;
    HttpServer(const uint16_t& port, func_t func)
        :port_(port)
        ,func_(func)
    {
        listensock_ = sock_.Socket();
        sock_.Bind(listensock_, port_);
        sock_.Listen(listensock_);
    }

    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        while (true)
        {
            std::string clientIp;
            uint16_t clientport;
            int sockfd = sock_.Accept(listensock_, &clientIp, &clientport);
            if (sockfd < 0) continue;
            if (fork() == 0)
            {
                close(listensock_);
                func_(sockfd);
                exit(0);
            }
            close(sockfd);
        }
    }

    ~HttpServer()
    {
        if (listensock_ >= 0) 
            close(listensock_);
    }
private:
    int listensock_;
    uint16_t port_;
    Sock sock_;
    func_t func_;
};